//
//  HostsManager.swift
//  Hostool
//
//  Created by Beyoug on 2024/11/7.
//

import Foundation

class HostsManager: ObservableObject {
    @Published var hostsContent: String = ""
    private let hostsPath = "/etc/hosts"
    
    func loadHostsFile() throws {
        let content = try String(contentsOfFile: hostsPath, encoding: .utf8)
        DispatchQueue.main.async {
            self.hostsContent = content
        }
    }
    
    func saveHostsFile() throws {
        let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent("hosts.tmp")
        try hostsContent.write(to: tempFile, atomically: true, encoding: .utf8)
        
        let script = """
        do shell script "cp '\(tempFile.path)' '\(hostsPath)'" with administrator privileges
        """
        
        var error: NSDictionary?
        if let scriptObject = NSAppleScript(source: script) {
            scriptObject.executeAndReturnError(&error)
            if let error = error {
                // 检查用户是否取消了操作
                if let errorCode = error[NSAppleScript.errorNumber] as? Int, errorCode == -128 {
                    throw NSError(domain: "HostsManager", code: errorCode, userInfo: [NSLocalizedDescriptionKey: "操作已取消"])
                } else {
                    throw NSError(domain: "HostsManager", code: 1, userInfo: [NSLocalizedDescriptionKey: error])
                }
            }
        } else {
            throw NSError(domain: "HostsManager", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法创建 AppleScript"])
        }
        
        try FileManager.default.removeItem(at: tempFile)
    }
}
